package org.etom.test.connector;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RpcTestServer extends HttpServlet {

  private static final long serialVersionUID = 1013061076041525536L;

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String responseFile = getResponseFile(req);
    if (null == responseFile)
      return;
    setResponseFile(responseFile, resp);
  }
  
  private String getResponseFile(HttpServletRequest req) throws IOException {
    BufferedReader buffReader = null;
    String response = null;
    String currentLine;
    try {
      buffReader = new BufferedReader(new InputStreamReader(req.getInputStream()));
      while ((currentLine = buffReader.readLine()) != null) {
        if (currentLine.indexOf(TestConstants.METHOD_GET_USER_COURSES) != -1) {
          response = TestConstants.GET_USER_COURSES_RESPONSE;
          break;
        } else if (currentLine.indexOf(TestConstants.METHOD_GET_USER) != -1) {
          response = TestConstants.GET_USER_RESPONSE;
          break;
        }
      }
    } finally {
      if (buffReader != null) {
        buffReader.close();
      }
    }
    return response;
  }
  
  private void setResponseFile(String responseFile, HttpServletResponse resp) throws IOException {
    BufferedInputStream buffInStream = null;
    ServletOutputStream servletOutStream = null;
    try {
      buffInStream = new BufferedInputStream(
          getClass().getResourceAsStream(responseFile));
      servletOutStream = resp.getOutputStream();
      byte[] buffer = new byte[512];
      int readBytes;
      while((readBytes = buffInStream.read(buffer)) != -1) {
        servletOutStream.write(buffer, 0, readBytes);
      }
    } finally {
      if (null != buffInStream) {
        buffInStream.close();
      }
      if (null != servletOutStream) {
        servletOutStream.close();
      }
    }
  }
  
}
